/**
 * settings.js - 用户设置页面脚本
 */

document.addEventListener('DOMContentLoaded', function() {
  // 检查用户登录状态
  if (ApiService.redirectIfNotAuthenticated()) {
    return;
  }
  
  // 初始化组件
  const topNavBar = new TopNavBar();
  topNavBar.init();
  
  const sideBar = new SideBar();
  sideBar.init('settings');
  
  // 加载用户设置
  loadUserSettings();
  
  // 初始化设置事件
  initSettingEvents();
  
  // 初始化模态框
  initModals();
});

/**
 * 加载用户设置
 */
function loadUserSettings() {
  // 这里应该从后端API获取用户设置信息
  // 目前使用模拟数据
  
  // 获取用户信息（如果有）
  const userInfoStr = localStorage.getItem('userInfo');
  let userInfo = null;
  
  if (userInfoStr) {
    try {
      userInfo = JSON.parse(userInfoStr);
    } catch (e) {
      console.error('Failed to parse user info', e);
    }
  }
  
  // 设置主题（从本地存储获取）
  const theme = localStorage.getItem('theme') || 'light';
  document.getElementById('theme-mode').value = theme;
  
  // 设置语言（从本地存储获取）
  const language = localStorage.getItem('language') || 'zh-CN';
  document.getElementById('language').value = language;
  
  // 设置其他选项（模拟数据）
  document.getElementById('auto-logout').checked = localStorage.getItem('autoLogout') !== 'false';
  document.getElementById('transaction-notification').checked = localStorage.getItem('transactionNotification') !== 'false';
  document.getElementById('system-notification').checked = localStorage.getItem('systemNotification') !== 'false';
  document.getElementById('transaction-alert').checked = localStorage.getItem('transactionAlert') !== 'false';
  document.getElementById('marketing-notification').checked = localStorage.getItem('marketingNotification') === 'true';
  document.getElementById('email-notification').checked = localStorage.getItem('emailNotification') !== 'false';
  document.getElementById('two-factor-auth').checked = localStorage.getItem('twoFactorAuth') === 'true';
  
  // 设置安全级别
  updateSecurityLevel();
}

/**
 * 初始化设置事件
 */
function initSettingEvents() {
  // 主题切换
  document.getElementById('theme-mode').addEventListener('change', function() {
    const theme = this.value;
    localStorage.setItem('theme', theme);
    Toast.success('主题设置已保存');
    
    // 应用主题（实际项目中应该更改CSS类或文件）
    if (theme === 'dark') {
      document.body.classList.add('dark-theme');
    } else {
      document.body.classList.remove('dark-theme');
    }
  });
  
  // 语言切换
  document.getElementById('language').addEventListener('change', function() {
    const language = this.value;
    localStorage.setItem('language', language);
    Toast.success('语言设置已保存，将在页面刷新后生效');
    
    // 在实际项目中，这里应该调用语言切换的API或重新加载页面
  });
  
  // 开关按钮事件
  const toggleSwitches = [
    { id: 'auto-logout', key: 'autoLogout' },
    { id: 'transaction-notification', key: 'transactionNotification' },
    { id: 'system-notification', key: 'systemNotification' },
    { id: 'transaction-alert', key: 'transactionAlert' },
    { id: 'marketing-notification', key: 'marketingNotification' },
    { id: 'email-notification', key: 'emailNotification' },
    { id: 'two-factor-auth', key: 'twoFactorAuth' }
  ];
  
  toggleSwitches.forEach(({ id, key }) => {
    document.getElementById(id).addEventListener('change', function() {
      localStorage.setItem(key, this.checked);
      
      // 如果是两因素认证，需要特殊处理
      if (id === 'two-factor-auth') {
        if (this.checked) {
          // 在实际项目中，这里应该跳转到两因素认证设置页面
          Toast.info('请完成双因素认证设置');
        } else {
          Toast.success('已关闭双因素认证');
        }
        
        // 更新安全级别
        updateSecurityLevel();
      } else {
        Toast.success('设置已更新');
      }
      
      // 在实际项目中，这里应该调用API保存设置
    });
  });
  
  // 修改密码按钮
  document.getElementById('change-password-btn').addEventListener('click', function() {
    document.getElementById('password-modal').style.display = 'block';
  });
  
  // 修改交易密码按钮
  document.getElementById('change-payment-password-btn').addEventListener('click', function() {
    document.getElementById('payment-password-modal').style.display = 'block';
  });
  
  // 管理设备按钮
  document.getElementById('manage-devices-btn').addEventListener('click', function() {
    Toast.info('设备管理功能正在开发中');
  });
  
  // 清除缓存按钮
  document.getElementById('clear-cache-btn').addEventListener('click', function() {
    // 清除本地存储中的非关键数据
    const keysToKeep = ['token', 'userInfo'];
    
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (!keysToKeep.includes(key)) {
        localStorage.removeItem(key);
      }
    }
    
    Toast.success('缓存已清除');
  });
  
  // 帮助与反馈按钮
  document.getElementById('help-feedback-btn').addEventListener('click', function() {
    Toast.info('帮助与反馈功能正在开发中');
  });
  
  // 关于系统按钮
  document.getElementById('about-btn').addEventListener('click', function() {
    Toast.info('系统版本: 1.0.0\n版权所有 © 2025 虚拟银行系统');
  });
  
  // 注销账户按钮
  document.getElementById('delete-account-btn').addEventListener('click', function() {
    if (confirm('警告：账户注销后将无法恢复，所有数据将被永久删除。是否确认注销账户？')) {
      // 在实际项目中，这里应该调用API进行账户注销
      Toast.info('账户注销功能已被管理员禁用，如需注销请联系客服');
    }
  });
}

/**
 * 初始化模态框
 */
function initModals() {
  // 密码修改模态框
  initPasswordModal();
  
  // 交易密码修改模态框
  initPaymentPasswordModal();
}

/**
 * 初始化密码修改模态框
 */
function initPasswordModal() {
  const modal = document.getElementById('password-modal');
  const closeBtn = modal.querySelector('.modal-close');
  const cancelBtn = document.getElementById('password-cancel-btn');
  const saveBtn = document.getElementById('password-save-btn');
  const form = document.getElementById('password-form');
  
  // 关闭按钮
  closeBtn.addEventListener('click', function() {
    modal.style.display = 'none';
    form.reset();
  });
  
  // 取消按钮
  cancelBtn.addEventListener('click', function() {
    modal.style.display = 'none';
    form.reset();
  });
  
  // 点击模态框外部关闭
  window.addEventListener('click', function(event) {
    if (event.target === modal) {
      modal.style.display = 'none';
      form.reset();
    }
  });
  
  // 保存按钮
  saveBtn.addEventListener('click', function() {
    const currentPassword = document.getElementById('current-password').value;
    const newPassword = document.getElementById('new-password').value;
    const confirmPassword = document.getElementById('confirm-password').value;
    
    // 简单验证
    if (!currentPassword) {
      Toast.error('请输入当前密码');
      return;
    }
    
    if (!newPassword) {
      Toast.error('请输入新密码');
      return;
    }
    
    if (newPassword.length < 8 || newPassword.length > 20) {
      Toast.error('新密码长度应为8-20位');
      return;
    }
    
    if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,20}$/.test(newPassword)) {
      Toast.error('新密码必须包含字母和数字');
      return;
    }
    
    if (newPassword !== confirmPassword) {
      Toast.error('两次输入的密码不一致');
      return;
    }
    
    // 调用API修改密码
    ApiService.put('/api/user/password', {
      oldPassword: currentPassword,
      newPassword: newPassword,
      confirmPassword: confirmPassword
    })
      .then(response => {
        if (response.code === 0) {
          Toast.success('密码修改成功');
          modal.style.display = 'none';
          form.reset();
          
          // 更新安全级别
          updateSecurityLevel();
        } else {
          Toast.error(response.message || '密码修改失败');
        }
      })
      .catch(error => {
        console.error('修改密码失败', error);
        Toast.error('密码修改失败，请稍后再试');
      });
  });
}

/**
 * 初始化交易密码修改模态框
 */
function initPaymentPasswordModal() {
  const modal = document.getElementById('payment-password-modal');
  const closeBtn = modal.querySelector('.modal-close');
  const cancelBtn = document.getElementById('payment-password-cancel-btn');
  const saveBtn = document.getElementById('payment-password-save-btn');
  const form = document.getElementById('payment-password-form');
  
  // 关闭按钮
  closeBtn.addEventListener('click', function() {
    modal.style.display = 'none';
    form.reset();
  });
  
  // 取消按钮
  cancelBtn.addEventListener('click', function() {
    modal.style.display = 'none';
    form.reset();
  });
  
  // 点击模态框外部关闭
  window.addEventListener('click', function(event) {
    if (event.target === modal) {
      modal.style.display = 'none';
      form.reset();
    }
  });
  
  // 保存按钮
  saveBtn.addEventListener('click', function() {
    const currentPassword = document.getElementById('current-payment-password').value;
    const newPassword = document.getElementById('new-payment-password').value;
    const confirmPassword = document.getElementById('confirm-payment-password').value;
    
    // 简单验证
    if (!currentPassword) {
      Toast.error('请输入当前交易密码');
      return;
    }
    
    if (!newPassword) {
      Toast.error('请输入新交易密码');
      return;
    }
    
    if (!/^\d{6}$/.test(newPassword)) {
      Toast.error('交易密码必须是6位数字');
      return;
    }
    
    if (newPassword !== confirmPassword) {
      Toast.error('两次输入的交易密码不一致');
      return;
    }
    
    // 调用API修改交易密码
    ApiService.put('/api/user/payment-password', {
      oldPassword: currentPassword,
      newPassword: newPassword
    })
      .then(response => {
        if (response.code === 0) {
          Toast.success('交易密码修改成功');
          modal.style.display = 'none';
          form.reset();
          
          // 更新安全级别
          updateSecurityLevel();
        } else {
          Toast.error(response.message || '交易密码修改失败');
        }
      })
      .catch(error => {
        console.error('修改交易密码失败', error);
        Toast.error('交易密码修改失败，请稍后再试');
      });
  });
}

/**
 * 更新安全级别
 */
function updateSecurityLevel() {
  // 检查安全级别
  let securityScore = 0;
  
  // 已设置交易密码 +1
  if (localStorage.getItem('hasPaymentPassword') === 'true') {
    securityScore += 1;
  }
  
  // 开启了两因素认证 +1
  if (localStorage.getItem('twoFactorAuth') === 'true') {
    securityScore += 1;
  }
  
  // 近期修改过密码 +1 (模拟数据)
  if (localStorage.getItem('passwordLastChanged')) {
    const lastChanged = new Date(localStorage.getItem('passwordLastChanged'));
    const now = new Date();
    const diffDays = Math.floor((now - lastChanged) / (1000 * 60 * 60 * 24));
    
    if (diffDays < 90) { // 3个月内修改过密码
      securityScore += 1;
    }
  }
  
  // 更新安全级别UI
  const progressElement = document.querySelector('.security-level-progress');
  const textElement = document.querySelector('.security-level-text');
  
  if (securityScore <= 1) {
    progressElement.className = 'security-level-progress low';
    textElement.className = 'security-level-text low';
    textElement.textContent = '低';
  } else if (securityScore === 2) {
    progressElement.className = 'security-level-progress medium';
    textElement.className = 'security-level-text medium';
    textElement.textContent = '中等';
  } else {
    progressElement.className = 'security-level-progress high';
    textElement.className = 'security-level-text high';
    textElement.textContent = '高';
  }
}
